<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
// 接口
import {
  createCompailationDataApi,
  deleteCompailationDataApi,
  updateCompailationDataApi,
  getCompailationDataApi,
  getUserIdList
} from "@/api/combo"
import { useTeamStore } from "@/store/modules/team"
import { useDepartmentStore } from "@/store/modules/department"
import { useUserStore } from "@/store/modules/user"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "Compilation"
})
const router = useRouter()
const compilationId = ref<any>(undefined)
const handleUpdate = (row: any) => {
  compilationId.value = row.id
  formData.name = row.name
  formData.sku = row.sku
  formData.open = row.open
  if (row.team) {
    formData.team = row.team.split(",")
  }
  if (row.userIds) {
    formData.userIds = row.userIds.split(",")
  }
  dialogVisible.value = true
}
// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除:${row.name}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCompailationDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getApplet()
    })
  })
}
// #endregion

// #region 增
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  sku: "",
  open: "",
  userIds: [],
  team: []
})
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入名称" }],
  sku: [{ required: true, trigger: "blur", message: "请输入编码" }]
  // open: [{ required: true, trigger: "blur", message: "请选择是否对分销商开放" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (compilationId.value === undefined) {
        createCompailationDataApi({
          name: formData.name,
          sku: formData.sku,
          open: formData.open,
          userIds: formData.userIds.join(),
          team: formData.team.join()
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getApplet()
        })
      } else {
        updateCompailationDataApi({
          id: compilationId.value,
          name: formData.name,
          open: formData.open,
          sku: formData.sku,
          userIds: formData.userIds.join(),
          team: formData.team.join()
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getApplet()
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  compilationId.value = undefined
  clearValidate()
  formData.name = ""
  formData.sku = ""
  formData.open = ""
  formData.team = []
  formData.userIds = []
}
// #endregion

// #region 查
const userStore = useUserStore()
const tableTotal = ref<number>()
const tableData = ref<any>([])
const getApplet = () => {
  getCompailationDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name,
    team: userStore.teamName
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
// #endregion
//跳转配置子套餐页面
const handleGoToChildSet = (row: any) => {
  console.log(row)
  router.push(`childset/?id=${row.id}`)
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getApplet, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}

/**监听 team 缓存 */
/**团队数据获取 */
const props1 = {
  multiple: true,
  emitPath: false,
  // checkStrictly: true,
  label: "name",
  value: "name"
}
const teamList = ref<any>([])
/**部门数据获取 */
const departmentList = ref<any>([])
/**部门团队组合数据 */
const departTeam = ref<any>([])
const teamStore = useTeamStore()
const departmentStore = useDepartmentStore()
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    teamList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**team END */
/**监听 department 缓存 */
departmentStore.getDepartmentFn()
watch(
  [() => departmentStore.departmentListStore],
  (newValue) => {
    departmentList.value = newValue.flat()
    /**实现部门团队数据合并 */
    departTeam.value = departmentList.value.map((item: any) => ({
      ...item,
      children: teamList.value.filter((childrenItem: any) => childrenItem.source === item.name)
    }))
    /**部门下无团队禁选 */
    departTeam.value.forEach((item: any) => {
      if (!item.children.length) {
        item.disabled = true
      }
      return item
    })
  },
  {
    immediate: true
  }
)
/**代理数据 */
const userIdList = ref<any>([])
const userListEffect = () => {
  getUserIdList({}).then((res: any) => {
    console.log(res)
    userIdList.value = res.data
  })
}
userListEffect()
/**END */
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="合集名称">
          <el-input v-model.trim="searchData.name" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="dialogVisible = true">添加套餐合集</el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="合集名称" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="left">
            <template #default="scope">
              <p>
                <el-button type="primary" text bg size="small" @click="handleGoToChildSet(scope.row)"
                  >配置子套餐</el-button
                >
              </p>
              <p>
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              </p>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="compilationId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="合集名称" label-width="120">
          <el-input type="textarea" v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sku" label="合集编码" label-width="120">
          <el-input v-model="formData.sku" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="team" label="可销售团队" label-width="120">
          <!-- <el-select v-model="formData.team" clearable filterable placeholder="请选择" multiple style="width: 240px">
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select> -->
          <el-cascader
            size="large"
            placeholder="可输入快速查询"
            :props="props1"
            :options="departTeam"
            v-model="formData.team"
            :filterable="true"
            :show-all-levels="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="open" label="对分销商展示" label-width="120">
          <el-select v-model="formData.open" clearable placeholder="请选择" style="width: 100%">
            <el-option key="1" label="是" :value="true" />
            <el-option key="2" label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="userIds" label="可销售分销商" label-width="120">
          <el-select
            :disabled="!formData.open"
            v-model="formData.userIds"
            clearable
            filterable
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in userIdList"
              :key="item.user_id"
              :label="item.user_name"
              :value="item.user_id + ''"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
